import { login, getUserInfo } from "@/api/user";
import { setToken, removeToken } from "@/utils/auth";
import dayjs from "dayjs";

const getDefaultState = () => {
  return {
    token: "",
    loginTime: "",
    userInfo: {
      id: "",
      userName: "",
      // 用户角色列表
      roles: [],
      // 用户头像
      avatar: "",
    },
  };
};

const userModule = {
  namespaced: true,
  state: getDefaultState(),
  mutations: {
    resetState: (state) => {
      Object.keys(state).forEach((key) => {
        if (Object.prototype.hasOwnProperty.call(getDefaultState(), key)) {
          state[key] = getDefaultState()[key];
        }
      });
    },
    setToken: (state, token) => {
      state.token = token;
    },
    // 设置用户登录时间
    setLoginTime(state, data) {
      state.loginTime = data;
    },
    // 设置用户信息
    setUserInfo(state, data) {
      state.userInfo = data;
    },
  },
  actions: {
    // 登陆
    // eslint-disable-next-line
    async login({ commit }, data) {
      const result = await new Promise((resolve, reject) => {
        login(data)
          .then((res) => {
            if (res) {
              commit("setToken", res.data);
              setToken(res.data);
              commit(
                "setLoginTime",
                dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
              );
              resolve(res);
            } else {
              reject();
            }
          })
          .catch((err) => reject(err));
      });
      return result;
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
      // 异步获取用户信息
      const result = await new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            // 存储用户信息到浏览器缓存
            commit("setUserInfo", res.data);
            resolve(res);
          })
          .catch((err) => reject(err));
      });
      return result;
    },
    // user logout
    logout({ commit }) {
      return new Promise((resolve) => {
        removeToken(); // must remove  token  first
        commit("resetState");
        resolve();
      });
    },
    // remove token
    resetToken({ commit }) {
      return new Promise((resolve) => {
        removeToken(); // must remove  token  first
        commit("resetState");
        resolve();
      });
    },
  },
};

export default userModule;
